package org.system.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.system.core.common.Result;

import javax.servlet.http.HttpServletRequest;

/**
 * @author baoRoot
 */
@RestControllerAdvice
public class GlobalException {

    private static final Logger logger = LoggerFactory.getLogger(GlobalException.class);

    @ExceptionHandler(value = ServiceException.class)
    public Result<String> customException(Exception e) {
        logger.warn("自定义异常捕获: {}", e.getMessage());
        return Result.fail(400, e.getMessage(), null);
    }

    @ExceptionHandler(value = UserNotExistsException.class)
    public Result<String> userNotExistsException(Exception e) {
        logger.warn("登录用户异常捕获: {}", e.getMessage());
        return Result.fail(400, e.getMessage(), null);
    }

    @ExceptionHandler(value = UserPasswordNotMatchException.class)
    public Result<String> userPasswordNotMatchException(Exception e) {
        logger.warn("登录用户密码异常捕获: {}", e.getMessage());
        return Result.fail(400, e.getMessage(), null);
    }

    @ExceptionHandler(value = UserVerifyException.class)
    public Result<String> userVerifyException(Exception e) {
        logger.warn("用户校验异常: {}", e.getMessage());
        return Result.fail(400, e.getMessage(), null);
    }

    @ExceptionHandler(value = RegisterException.class)
    public Result<String> registerException(Exception e) {
        logger.warn("用户注册异常: {}", e.getMessage());
        return Result.fail(400, e.getMessage(), null);
    }

    @ExceptionHandler(value = AuthorityException.class)
    public Result<String> authorityException(Exception e) {
        logger.warn("没有权限异常捕获: {}", e.getMessage());
        return Result.fail(403, e.getMessage(), null);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        logger.info("捕获方法异常：{}", e.getMessage());
        String message = e.getBindingResult().getFieldError().getDefaultMessage();
        return Result.fail(400, message, null);
    }

    @ExceptionHandler(Exception.class)
    public Result<String> handleException(Exception e, HttpServletRequest request) {
        String requestURI = request.getRequestURI();
        logger.error("请求地址{},发生系统异常", requestURI, e);
        return Result.fail(400, e.getMessage(), null);
    }

}
